package org.example.service;

import com.alibaba.dubbo.config.annotation.Service;
import org.example.api.TagApi;
import org.example.common.Result;
import org.example.mapper.TagMapper;
import org.example.model.Tag;
import org.example.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Service(interfaceClass = TagApi.class, version = "1.0.0", timeout = 35000)
public class TagService implements TagApi {

    private static final Object QUERY_ALL_TAG_BY_USER_ID = new Object();
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public Result<List<Tag>> queryAllTagByUserId(Long userId) {
        // tag:user:{userId}
        String key = "tag:user:" + userId;

        List<Tag> tags = redisUtil.getObject(key);
        if (CollectionUtils.isEmpty(tags)) {
            synchronized (QUERY_ALL_TAG_BY_USER_ID) {
                tags = redisUtil.getObject(key);
                if (CollectionUtils.isEmpty(tags)) {
                    tags = tagMapper.queryAllTagByUserId(userId);
                    if (!CollectionUtils.isEmpty(tags)) {
                        redisUtil.setObject(key, tags, 60 * 1000);
                    }
                }
            }
        }
        return Result.ok(tags);
    }
}
